package com.cloudbroker.openapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.*;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSFields;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.HSBCPSVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.*;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.ImgVerifyForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.WhiteListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.WhiteListFormData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.SaveLoginInformationForm;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.business.FansT2BizService;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.business.HistoryT2BizService;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.business.UserManagerT2BizService;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.export.WeixinT2BizService;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.ext.annotation.SaveLog;
import com.cloudbroker.bcs.platform.dav.common.util.RequestUtil;
import com.cloudbroker.bcs.platform.dav.common.util.WhiteListFileUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cloudbroker.bcs.platform.dav.common.util.RequestUtil.getSingleParameterMapForBody;

/**
 * Created by xuyn15828 on 2016/5/6.
 */
@Controller
public class AccountController {
    @Resource
    private UserManagerT2BizService userT2;
    
    @Resource
    private FansT2BizService fansT2;
    
    @Resource
    private HistoryT2BizService historyT2;
    
    @Resource
    private WeixinT2BizService weixinT2BizService;
    
    /**
     * 获取图片验证码
     */
    @ResponseBody
    @RequestMapping("/func_account_imgverify")
    @SaveLog(remark = "获取图片验证码")
    public HSBCPSBackVO funcAccountImgverify(HttpServletRequest request, HttpServletResponse response,
            String jsonpcallback) {
        ImgVerifyForm form = getSingleParameterMapForBody(request, ImgVerifyForm.class);
        ImgVerifyFormBackForm result = (ImgVerifyFormBackForm) userT2.funcAccountImgverify(form);
        if (ValueUtil.getString(result.getError_no()).equals("0")) {
            String verifyCode = ValueUtil.getString(result.getVerify_code());
            int w = 107, h = 30;
            try {
                VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return VOUtil.genSuccessBackVo();
        }
        return VOUtil.setJsonpResult(result, jsonpcallback);
    }
    
    @ResponseBody
    @RequestMapping("/func_get_userinfo_encode")
    @SaveLog(remark = "获取加密后的用户信息")
    public UserInfoEncode funcGetUserInfoEncode(HttpServletRequest request, HttpServletResponse response,
            String jsonpcallback) {
        
        HSBCPSVO param = getSingleParameterMapForBody(request, HSBCPSVO.class);
        UserInfoBackForm info = fansT2.funcUserInfoQry(param);
        UserInfoEncode encode = new UserInfoEncode();
        if (!VOUtil.isSuccess(info)) {
            encode = VOUtil.genErrorResult(info.getError_no(), UserInfoEncode.class);
            encode.setError_info(info.getError_info());
            return encode;
        }
        String avatar = null;
        if (StringUtils.isNotBlank(info.getCustomer_avatar())) {
            avatar = ConfigValues.getInterfaceOssAddr() + info.getCustomer_avatar()
                    + "/92f17e36e6cf0a8083ff435fc708a372";
        }
        JSONObject infoJson = new JSONObject();
        infoJson.put("user_id", info.getCustomer_id());
        infoJson.put("user_name", info.getCustomer_name());
        infoJson.put("user_head", avatar);
        infoJson.put("mobile", info.getMobile());
        encode.setEncrypt_info(DESUtil.encode(infoJson.toJSONString()));
        return VOUtil.setSuccessResult(encode);
    }
    
    /**
     * 数据库数据导入搜索引擎
     * @param request
     * @param jsonpcallback
     * @return
     */
    @ResponseBody
    @RequestMapping("/func_history_import_searchengine")
    @SaveLog(remark = "搜索引擎数据导入")
    public HSBCPSBackVO funcImportSearchEngine(HttpServletRequest request, String jsonpcallback) {
        HSBCPSVO form = getSingleParameterMapForBody(request, HSBCPSVO.class);
        return VOUtil.setJsonpResult(historyT2.funcImportSearchEngine(form), jsonpcallback);
    }
    
    /**
     * 数据库数据导入搜索引擎
     * @param request
     * @param jsonpcallback
     * @return
     */
    @ResponseBody
    @RequestMapping("/func_save_login_information")
    @SaveLog(remark = "保存登录信息")
    public HSBCPSBackVO funcSaveLoginInformation(HttpServletRequest request, String jsonpcallback) {
        SaveLoginInformationForm form = getSingleParameterMapForBody(request, SaveLoginInformationForm.class);
        form.setIp(getRemoteIP(request));
        form.setBrowser(request.getHeader("User-agent"));
        return VOUtil.setJsonpResult(weixinT2BizService.funcSaveLoginInformation(form), jsonpcallback);
    }
    
    /**
     * 用户外网IP信息获取
     * @param request
     * @param jsonpcallback
     * @return
     */
    @ResponseBody
    @RequestMapping("/func_parse_login_info")
    @SaveLog(remark = "解析用户登录IP")
    public UserBrowserInfoBack funcParseLoginInfo(HttpServletRequest request, String jsonpcallback) {
        UserBrowserInfoBack result = new UserBrowserInfoBack();
        result.setLocal_ip(getRemoteIP(request));
        return VOUtil.setJsonpResult(VOUtil.setSuccessResult(result), jsonpcallback);
    }
    
    @ResponseBody
    @RequestMapping("/func_whitelist_import")
    @SaveLog(remark = "白名单导入")
    public HSBCPSBackVO funcWhitelistImport(MultipartHttpServletRequest request) {
        WhiteListFormData form = getSingleParameterMapForBody(request, WhiteListFormData.class);
        MultipartFile multipartFile = request.getFile(HSBCPSFields.FILE);
        List<WhiteListForm> mobileList = WhiteListFileUtil.parseFile(multipartFile);
        form.setDataList(mobileList);
        return VOUtil.setJsonpResult(userT2.funcWhitelistImport(form), null);
    }
    
    @ResponseBody
    @RequestMapping("/func_whitelist_output")
    @SaveLog(remark = "白名单导出")
    public HSBCPSBackVO funcWhitelistOutput(HttpServletRequest request, HttpServletResponse response,
            String jsonpcallback) {
        HSBCPSVO form = getSingleParameterMapForBody(request, HSBCPSVO.class);
        WhiteListBackForm mobileList = userT2.funcWhitelistOutput(form);
        if (VOUtil.isSuccess(mobileList)) {
            WhiteListFileUtil.outputFile(response, mobileList.getData_list());
            return VOUtil.genSuccessBackVo();
        }
        return mobileList;
    }
    
    @ResponseBody
    @RequestMapping("/getYunjiUserinfoByToken")
    @SaveLog(remark = "获取用户信息")
    public Map<String, Object> getYunjiUserinfoByToken(HttpServletRequest request) {
        Map<String, String> map = RequestUtil.getSingleParameterMap(request);
        String token = map.get("token_id");
        HSBCPSVO param = new HSBCPSVO();
        param.setUser_token(token);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        UserInfoBackForm info = fansT2.funcUserInfoQry(param);
        if (VOUtil.isSuccess(info)) {
            Map<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("nick_name", info.getCustomer_name());
            if (!StringUtil.isBlank(info.getCustomer_avatar())) {
                dataMap.put("photo_url", ConfigValues.getInterfaceOssAddr() + info.getCustomer_avatar() + "/"
                        + token);
            }
            dataMap.put("mobile_tel", info.getMobile());
            resultMap.put("success", true);
            resultMap.put("data", dataMap);
            return resultMap;
        } else {
            resultMap.put("success", false);
            resultMap.put("error_no", info.getError_no());
            resultMap.put("error_code", info.getError_no());
            resultMap.put("error_info", info.getError_info());
            return resultMap;
        }
    }
    
    /**
     *
     * getRemoteIP:获取远程请求客户端的外网IP <br/>
     *
     * @param request
     *            请求实体对象
     * @return ip 外网ip<br/>
     */
    public static String getRemoteIP(HttpServletRequest request) {
        String ipAddress = null;
        //ipAddress = this.getRequest().getRemoteAddr();
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                if (null != inet) {
                    ipAddress = inet.getHostAddress();
                }
            }
            
        }
        
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
    
}
